﻿//Description:推送排产下发回收、报工（完工）和撤销数据到BPM
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer: 
//create Date:
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using Newtonsoft.Json;
using UFC.Common;
using Newtonsoft.Json.Linq;

namespace SendCommissioningData
{
  public  class SendApsAndReportToBPM
    {
        private const string bpm_apsInfoSend = "bpm_apsInfoSend";//排产下发后
        private const string bpm_apsInfoRecycle = "bpm_apsInfoRecycle";//排产回收
        private const string bpm_report = "bpm_report";//完工
        private const string bpm_reportRecycle = "bpm_reportRecycle";//完工撤销

      /// <summary>
      /// 方法入口
      /// BPM推送的数据通过触发器放到sendtoothersystemdata表,接口从sendtoothersystemdata表取数据
      /// </summary>
      public void RunMain()
      {
          //推送排产下发数据
          sendApsInfoToBPM();
          //推送排产回收数据
          sendApsCycleInfoToBPM();
          //报工数据
          sendReportInfoToBPM();
          //报工撤回
          sendReportCycleInfoToBPM();
      }

      /// <summary>
      /// 获取需要推送给BPM的下发数据
      /// 工装工具有重复工装时取最大数，辅材有重复时求和 add:wangjh 20250318
      /// </summary>
      /// <param name="containerId"></param>
      /// <param name="stepId"></param>
      /// <returns></returns>
      public DataTable getApsInfoSend(string containerId,string stepId) {

          String sql = @"select fa.factoryname,fa.factoryid,al.workcenterid,wc.workcentername,al.teamid,t.teamname,m.mfgordername AUFNR,
cci.productname AMATNR,m.qty AERFMG,cci.containerid,cci.containername,al.workflowstepid,al.workflowstepname,
substr(al.workflowstepname,0,instr(al.workflowstepname,'-')-1) WORKFLOWSTEPNO,
to_char(al.starttime,'yyyy-mm-dd hh24:mi:ss') NDATE,to_char(al.endtime,'yyyy-mm-dd hh24:mi:ss') EDATE,rd.resourceid WORKSTATIONID,
rd.resourcename WORKSTATIONNO,rd.description WORKSTATIONNAME,cci.bomid,cci.workflowid,al.specid,e.employeename,al.qty apsqty
from sendtoothersystemdata sd
left join apsplandetail al on al.apsplandetailid=sd.parentid
inner join containercurrentinfo cci on cci.containerid=al.containerid
left join factory fa on fa.factoryid=cci.originalfactoryid
left join workcenter wc on wc.workcenterid=al.workcenterid
left join team t on t.teamid=al.teamid
left join mfgorder m on m.mfgorderid=cci.mfgorderid
left join resourcedef rd on rd.resourceid=al.resourceid
left join employee e on e.employeeid=al.outemp
inner join sendtoothersystemdatadetail sdd on sdd.sendtoothersystemdataid=sd.id
where sdd.sendtype='" + bpm_apsInfoSend + "' and sdd.issend=0 ";
              sql += string.Format(" and sd.containerid='{0}' and sd.workflowstepid='{1}' ", containerId, stepId);    

          DataTable apsInfo = OracleHelper.Query(sql).Tables[0];

          DataTable resultDt = apsInfo.Clone();
          resultDt.Columns.AddRange(new DataColumn[]{
            new DataColumn("MATNR"),new DataColumn("ZEINR"),new DataColumn("MAKTX"),new DataColumn("ERFMG")
          });
          if (apsInfo.Rows.Count == 0) {
              return resultDt;
          }
          //需求物料包含—工装、辅材、配套件（BOM）
          string bomId = apsInfo.Rows[0]["bomid"].ToString();
          //处理bom需求物料
          if (!string.IsNullOrWhiteSpace(bomId)) {
              String bomSql = @"select p.materialcode MATNR,pb1.productname ZEINR,p.description MAKTX,pm.qtyrequired ERFMG,NVL(SB.REVOFRCDID,PM.SPECID) SPECID  from bom b
left join productmateriallistitem pm on pm.bomid=b.bomid
LEFT JOIN productbase pb ON pb.productbaseid=pM.productbaseid 
LEFT JOIN PRODUCT P ON P.PRODUCTID=NVL(PB.REVOFRCDID,PM.PRODUCTID)
LEFT JOIN PRODUCTBASE PB1 ON PB1.PRODUCTBASEID=P.PRODUCTBASEID
LEFT JOIN SPECBASE SB ON SB.SPECBASEID=PM.SPECBASEID
LEFT JOIN SPEC S ON S.SPECID=NVL(SB.REVOFRCDID,PM.SPECID)
where b.bomid='{0}'";
              DataTable bomDt = OracleHelper.Query(string.Format(bomSql, bomId)).Tables[0];
              //筛选出挂BOM的工序
              List<String> bomSpecIds = bomDt.AsEnumerable()
                               .Select(row => row.Field<string>("SPECID"))
                               .Distinct()
                               .ToList();
              foreach (String specId in bomSpecIds) {
                  foreach (DataRow spec in apsInfo.Select("specid='"+specId+"'")) {
                      foreach (DataRow bomSpec in bomDt.Select("specid='" + spec["specid"].ToString() + "'"))
                      {
                          resultDt.ImportRow(spec);
                          resultDt.Rows[resultDt.Rows.Count - 1]["MATNR"] = bomSpec["MATNR"];
                          resultDt.Rows[resultDt.Rows.Count - 1]["ZEINR"] = bomSpec["ZEINR"];
                          resultDt.Rows[resultDt.Rows.Count - 1]["MAKTX"] = bomSpec["MAKTX"];
                          resultDt.Rows[resultDt.Rows.Count - 1]["ERFMG"] = Convert.ToInt32( bomSpec["ERFMG"]) * Convert.ToInt32(spec["apsqty"]);
                      }
                  }
              }

          }
          //处理工装信息
          string workflowId=apsInfo.Rows[0]["workflowid"].ToString();
          String toolSql = @"select ct.cuttoolname MATNR,ct.drawingno ZEINR,ct.description MAKTX,wt.qty ERFMG,ws.workflowstepid,null stepinfoid from workflowstep ws
left join workflowsteptools wt on wt.workflowstepid=ws.workflowstepid
inner join cuttool ct on ct.cuttoolid=wt.tools
where ws.workflowid ='{0}' and ws.workflowstepid='{1}'
union all
select mt.measuretoolname MATNR,mt.drawingno ZEINR,mt.description MAKTX,wt.qty ERFMG,ws.workflowstepid,null stepinfoid from workflowstep ws
left join workflowsteptools wt on wt.workflowstepid=ws.workflowstepid
inner join MeasureTool mt on mt.measuretoolid=wt.tools
where ws.workflowid ='{0}' and ws.workflowstepid='{1}'
union all
select st.specialtoolname MATNR,st.drawingno ZEINR,st.description MAKTX,wt.qty ERFMG,ws.workflowstepid,null stepinfoid from workflowstep ws
left join workflowsteptools wt on wt.workflowstepid=ws.workflowstepid
inner join SpecialTool st on st.specialtoolid=wt.tools
where ws.workflowid ='{0}' and ws.workflowstepid='{1}'";

          DataTable toolDt = OracleHelper.Query(String.Format(toolSql, workflowId, stepId)).Tables[0];
          //查询工步上的工装信息
          toolSql = @"select ct.cuttoolname MATNR,ct.drawingno ZEINR,ct.description MAKTX,st.qty ERFMG,sf.workflowstepid,sf.stepinfoid from stepinfo sf
left join stepinfotools st on st.stepinfoid=sf.stepinfoid
inner join cuttool ct on ct.cuttoolid=st.tools
where sf.workflowstepid ='{0}'
union all
select mt.measuretoolname MATNR,mt.drawingno ZEINR,mt.description MAKTX,st.qty ERFMG,sf.workflowstepid,sf.stepinfoid from stepinfo sf
left join stepinfotools st on st.stepinfoid=sf.stepinfoid
inner join MeasureTool mt on mt.measuretoolid=st.tools
where sf.workflowstepid ='{0}'
union all
select stt.specialtoolname MATNR,stt.drawingno ZEINR,stt.description MAKTX,st.qty ERFMG,sf.workflowstepid,sf.stepinfoid from stepinfo sf
left join stepinfotools st on st.stepinfoid=sf.stepinfoid
inner join SpecialTool stt on stt.specialtoolid=st.tools
where sf.workflowstepid ='{0}'";
          DataTable toolDt2 = OracleHelper.Query(string.Format(toolSql, stepId)).Tables[0];

          toolDt.Merge(toolDt2);

          if (toolDt.Rows.Count > 0)
          {
              //筛选出挂工装的工序
              //List<String> toolWorkflowStepIds = toolDt.AsEnumerable()
              //                 .Select(row => row.Field<string>("workflowstepid"))
              //                 .Distinct()
              //                 .ToList();
              //foreach (String workflowStepId in toolWorkflowStepIds)
              //{
              //    foreach (DataRow row in apsInfo.Select("workflowstepid='" + workflowStepId + "'"))
              //    {
              //        foreach (DataRow toolRow in toolDt.Select("workflowstepid='" + row["workflowstepid"].ToString() + "'"))
              //        {
              //            resultDt.ImportRow(row);
              //            resultDt.Rows[resultDt.Rows.Count - 1]["MATNR"] = toolRow["MATNR"];
              //            resultDt.Rows[resultDt.Rows.Count - 1]["ZEINR"] = toolRow["ZEINR"];
              //            resultDt.Rows[resultDt.Rows.Count - 1]["MAKTX"] = toolRow["MAKTX"];
              //            resultDt.Rows[resultDt.Rows.Count - 1]["ERFMG"] = toolRow["ERFMG"];
              //        }
              //    }
              //}

              //工序上的工装特殊处理,相同工装取最大数量 add:wangjh 20250319
              foreach (DataRow row in apsInfo.Rows) {
                  foreach (DataRow toolRow in toolDt.Rows)
                  {
                      DataRow[] resultRows = resultDt.Select(string.Format("MATNR='{0}'", toolRow["MATNR"].ToString()));
                      if (resultRows.Length > 0)
                      {
                          if (!toolRow.IsNull("ERFMG") && int.Parse(toolRow["ERFMG"].ToString()) > int.Parse(resultRows[0]["ERFMG"].ToString()))
                          {
                              resultRows[0]["ERFMG"] = toolRow["ERFMG"];
                          }
                      }
                      else
                      {
                          resultDt.ImportRow(row);
                          resultDt.Rows[resultDt.Rows.Count - 1]["MATNR"] = toolRow["MATNR"];
                          resultDt.Rows[resultDt.Rows.Count - 1]["ZEINR"] = toolRow["ZEINR"];
                          resultDt.Rows[resultDt.Rows.Count - 1]["MAKTX"] = toolRow["MAKTX"];
                          resultDt.Rows[resultDt.Rows.Count - 1]["ERFMG"] = toolRow["ERFMG"] is Nullable ? 1 : toolRow["ERFMG"];
                      }
                  }
              }           
              
          }

          //处理辅材信息
          String auxSql = @"select am.auxmaterialname MATNR,'' ZEINR,am.description MAKTX,wt.qty ERFMG,ws.workflowstepid,null stepinfoid from workflowstep ws
left join workflowsteptools wt on wt.workflowstepid=ws.workflowstepid
inner join auxmaterial am on am.auxmaterialid=wt.tools
where ws.workflowid ='{0}' and ws.workflowstepid='{1}'";

          DataTable auxDt = OracleHelper.Query(String.Format(auxSql, workflowId,stepId )).Tables[0];

          auxSql = @"select am.auxmaterialname MATNR,'' ZEINR,am.description MAKTX,st.qty ERFMG,sf.workflowstepid,null stepinfoid from stepinfo sf
left join stepinfotools st on st.stepinfoid=sf.stepinfoid
inner join auxmaterial am on am.auxmaterialid=st.tools
where sf.workflowstepid='{0}'";
          DataTable auxDt2 = OracleHelper.Query(String.Format(auxSql, stepId)).Tables[0];

          auxDt.Merge(auxDt2);

          if (auxDt.Rows.Count > 0)
          {
              //筛选出挂辅材的工序
              //List<String> auxWorkflowStepIds = auxDt.AsEnumerable()
              //                 .Select(row => row.Field<string>("workflowstepid"))
              //                 .Distinct()
              //                 .ToList();

              //foreach (String workflowStepId in auxWorkflowStepIds)
              //{
              //    foreach (DataRow row in apsInfo.Select("workflowstepid='" + workflowStepId + "'"))
              //    {
              //        foreach (DataRow auxRow in auxDt.Select("workflowstepid='" + row["workflowstepid"].ToString() + "'"))
              //        {
              //            resultDt.ImportRow(row);
              //            resultDt.Rows[resultDt.Rows.Count - 1]["MATNR"] = auxRow["MATNR"];
              //            resultDt.Rows[resultDt.Rows.Count - 1]["ZEINR"] = auxRow["ZEINR"];
              //            resultDt.Rows[resultDt.Rows.Count - 1]["MAKTX"] = auxRow["MAKTX"];
              //            resultDt.Rows[resultDt.Rows.Count - 1]["ERFMG"] = Convert.ToInt32(auxRow["ERFMG"]) * Convert.ToInt32(row["apsqty"]);
              //        }
              //    }
              //}

              //工序上的辅材特殊处理，遇到相同的求和 add:wangjh 20250319
              foreach (DataRow row in apsInfo.Rows) {
                  foreach (DataRow auxRow in auxDt.Rows) {
                      DataRow[] resultRows = resultDt.Select(string.Format("MATNR='{0}'", auxRow["MATNR"].ToString()));
                      if (resultRows.Length > 0)
                      {
                          int nowQty =  Convert.ToInt32(row["apsqty"])*int.Parse(auxRow["ERFMG"].ToString());
                          int preQty = Convert.ToInt32(resultRows[0]["ERFMG"]);
                          resultRows[0]["ERFMG"] = preQty+nowQty;
                      }
                      else {
                          resultDt.ImportRow(row);
                          resultDt.Rows[resultDt.Rows.Count - 1]["MATNR"] = auxRow["MATNR"];
                          resultDt.Rows[resultDt.Rows.Count - 1]["ZEINR"] = auxRow["ZEINR"];
                          resultDt.Rows[resultDt.Rows.Count - 1]["MAKTX"] = auxRow["MAKTX"];
                          resultDt.Rows[resultDt.Rows.Count - 1]["ERFMG"] = Convert.ToInt32(auxRow["ERFMG"]) * Convert.ToInt32(row["apsqty"]);
                      }
                  }
              }

          }
          //if (resultDt.Rows.Count == 0) {//此序没有物料需求信息
          //    resultDt.Merge(apsInfo);
          //}
          resultDt.AcceptChanges();
          return resultDt;

      }

      /// <summary>
      /// 推送排产下发数据到BPM 
      /// </summary>
      public void sendApsInfoToBPM() {

          //查询需要推送的批次，一次处理100个批次的
          DataTable conDt = OracleHelper.Query(@"select * from (
select sd.containerid,sd.workflowstepid from sendtoothersystemdata sd 
inner join sendtoothersystemdatadetail sdd on sdd.sendtoothersystemdataid=sd.id
where sdd.sendtype='" + bpm_apsInfoSend + @"' and sdd.issend=0 and sdd.lastchangedate>=sysdate-7
AND EXISTS (SELECT 1 FROM containercurrentinfo cci WHERE cci.containerid=sd.containerid)
group by sd.containerid,sd.workflowstepid,sdd.lastchangedate
ORDER BY sdd.lastchangedate
) where rownum<=500").Tables[0];
          List<String> conIds = conDt.AsEnumerable()
                             .Select(row => row.Field<string>("containerid"))
                             .Distinct()
                             .ToList();

          foreach (String conId in conIds)
          {
              DataTable conRe = new DataTable();
              string stepIds = "";

              foreach (DataRow conRow in conDt.Select("containerid='" + conId + "'"))
              {
                  stepIds += "'" + conRow["workflowstepid"].ToString() + "',";
                  //此序的排产及物料需求信息
                  DataTable re = getApsInfoSend(conId, conRow["workflowstepid"].ToString());
                  conRe.Merge(re);
              }
              if (!string.IsNullOrWhiteSpace(stepIds))
              {
                  stepIds = stepIds.Trim(',');
              }
              if (conRe.Rows.Count == 0) {
                  //更新sendtoothersystemdata表
                  OracleHelper.ExecuteSql(string.Format(@"update sendtoothersystemdatadetail sdd set sdd.lastchangedate=sysdate,sdd.issend='1' 
where sdd.sendtype='{0}' and sdd.issend='0' and sdd.sendtoothersystemdataid in (
select sd.id from sendtoothersystemdata sd where sd.containerid='{1}' and sd.workflowstepid in ({2})
)", bpm_apsInfoSend, conId, stepIds));
                  continue;
              }
              //操作人
              string SAPUSERID = conRe.Rows[0]["employeename"].ToString();
              //移除一些不需要的列
              conRe.Columns.Remove("BOMID"); conRe.Columns.Remove("WORKFLOWID"); conRe.Columns.Remove("SPECID"); conRe.Columns.Remove("employeename");
              String json = JsonConvert.SerializeObject(conRe);

              try
              {
                  //调用BPM接口
                  LogHelp.WriteLog("推送BPM排产下发数据：" + json);
                  BpmWebService1.wzqlc_WSApi api = new BpmWebService1.wzqlc_WSApi();
                  var re = api.busiService(SAPUSERID, "MFS1001", json);
                  LogHelp.WriteLog("推送BPM排产下发数据-返回信息：" + re);

                  //插入writetoothersystem表
                  var JsonObj = JObject.Parse(re); //JObject.Parse(re);

                  if (JsonObj["mtype"].ToString() == "S")//返回成功
                  {
                      //记录日志表
                      Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_apsInfoSend},
                        {"SendXml",json},{"ResXml",re},{"IsSuccess","0"},{"ContainerID",conId},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                      OracleDAL.InserOtherSystemRecord(recordPara);
                  }
                  else
                  {
                      //记录日志表
                      Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_apsInfoSend},
                        {"SendXml",json},{"ResXml",re},{"IsSuccess","1"},{"ContainerID",conId},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                      OracleDAL.InserOtherSystemRecord(recordPara);

                  }

              }
              catch (Exception ex)
              {
                  LogHelp.WriteError("推送BPM排产下发数据异常", ex);
                  //记录日志表
                  Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_apsInfoSend},
                        {"SendXml",json},{"ResXml",ex.Message +ex.StackTrace },{"IsSuccess","1"},{"ContainerID",conId},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                  OracleDAL.InserOtherSystemRecord(recordPara);
              }
              finally
              {
                  //更新sendtoothersystemdata表
                  OracleHelper.ExecuteSql(string.Format(@"update sendtoothersystemdatadetail sdd set sdd.lastchangedate=sysdate,sdd.issend='1' 
where sdd.sendtype='{0}' and sdd.issend='0' and sdd.sendtoothersystemdataid in (
select sd.id from sendtoothersystemdata sd where sd.containerid='{1}' and sd.workflowstepid in ({2})
)", bpm_apsInfoSend, conId, stepIds));
              }

          }
      }

      /// <summary>
      /// 推送排产回收数据到BPM
      /// </summary>
      public void sendApsCycleInfoToBPM() {
          //回收的数据
          DataTable dt = OracleHelper.Query(@"select * from (
select sd.containerid,sd.workflowstepid from sendtoothersystemdata sd 
inner join sendtoothersystemdatadetail sdd on sdd.sendtoothersystemdataid=sd.id
where sdd.sendtype='" + bpm_apsInfoRecycle + @"' and sdd.issend=0 and sdd.lastchangedate>=sysdate-7
group by sd.containerid,sd.workflowstepid
) where rownum<=500").Tables[0];

          List<String> conIds = dt.AsEnumerable()
                            .Select(row => row.Field<string>("containerid"))
                            .Distinct()
                            .ToList();

          foreach (String conId in conIds)
          {
              DataTable conRe =dt.Clone();//dt.Select("containerid='" + conId + "'").CopyToDataTable ();
              string stepIds = "";
              foreach (DataRow conRow in dt.Select("containerid='" + conId + "'"))
              {
                  stepIds += "'" + conRow["workflowstepid"].ToString() + "',";
                  conRe.ImportRow(conRow);
              }
              if (!string.IsNullOrWhiteSpace(stepIds))
              {
                  stepIds = stepIds.Trim(',');
              }

              String json = JsonConvert.SerializeObject(conRe);
              try
              {
                  //调用BPM接口
                  LogHelp.WriteLog("推送BPM排产回收数据：" + json);
                  BpmWebService1.wzqlc_WSApi api = new BpmWebService1.wzqlc_WSApi();
                  var re = api.busiService("","MFS1002", json);
                  LogHelp.WriteLog("推送BPM排产回收数据-返回信息：" + re);

                  //插入writetoothersystem表
                  var JsonObj = JObject.Parse(re);
                  if (JsonObj["mtype"].ToString() == "S")//返回成功
                  {
                      //记录日志表
                      Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_apsInfoRecycle},
                        {"SendXml",json},{"ResXml",re},{"IsSuccess","0"},{"ContainerID",conId},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                      OracleDAL.InserOtherSystemRecord(recordPara);
                  }
                  else
                  {
                      //记录日志表
                      Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_apsInfoRecycle},
                        {"SendXml",json},{"ResXml",re},{"IsSuccess","1"},{"ContainerID",conId},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                      OracleDAL.InserOtherSystemRecord(recordPara);

                  }
              }
              catch (Exception ex)
              {
                  LogHelp.WriteError("推送BPM排产回收数据异常", ex);
                  //记录日志表
                  Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_apsInfoRecycle},
                        {"SendXml",json},{"ResXml",ex.Message +ex.StackTrace },{"IsSuccess","1"},{"ContainerID",conId},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                  OracleDAL.InserOtherSystemRecord(recordPara);
              }
              finally
              {
                  //更新sendtoothersystemdata表
                  OracleHelper.ExecuteSql(string.Format(@"update sendtoothersystemdatadetail sdd set sdd.lastchangedate=sysdate,sdd.issend='1' 
where sdd.sendtype='{0}' and sdd.issend='0' and sdd.sendtoothersystemdataid in (
select sd.id from sendtoothersystemdata sd where sd.containerid='{1}' and sd.workflowstepid in ({2})
)", bpm_apsInfoRecycle, conId, stepIds));
              }
          
          }
      }

      /// <summary>
      /// 推送报工信息到BPM,实际是完工
      /// </summary>
      public void sendReportInfoToBPM() {
          string strSql = @"select sd.containerid,sd.workflowstepid,sdd.id from sendtoothersystemdata sd 
inner join sendtoothersystemdatadetail sdd on sdd.sendtoothersystemdataid=sd.id
where sdd.sendtype='" + bpm_report + "' and sdd.issend='0' and sdd.lastchangedate>=sysdate-7 and rownum<1000";

          DataTable dt = OracleHelper.Query(strSql).Tables[0];
          if (dt.Rows.Count == 0)
              return;
          DataTable jsonDt = dt.Copy();
          jsonDt.Columns.Remove("id");

          String json = JsonConvert.SerializeObject(jsonDt);

          try {
              //调用BPM接口
              LogHelp.WriteLog("推送BPM报工数据：" + json);
              BpmWebService1.wzqlc_WSApi api = new BpmWebService1.wzqlc_WSApi();
              var re = api.busiService("","MFS1003", json);
              LogHelp.WriteLog("推送BPM报工数据-返回信息：" + re);

              var JsonObj = JObject.Parse(re);

              string isSuccess = "0";
              if (JsonObj["mtype"].ToString() == "S")//返回成功
              {
                  isSuccess = "0";
              }
              else {
                  isSuccess = "1";
              }
              foreach (DataRow dr in dt.Rows)
              {
                  //插入writetoothersystem表
                  Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_report},
                        {"SendXml",json},{"ResXml",re},{"IsSuccess",isSuccess},{"ContainerID",dr["ContainerID"].ToString ()},{"WorkflowStepId",dr["WorkflowStepId"].ToString ()}
                        ,{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                  OracleDAL.InserOtherSystemRecord(recordPara);
                  //更新sendtoothersystemdata表
                  OracleHelper.ExecuteSql(string.Format("update sendtoothersystemdatadetail sd set sd.lastchangedate=sysdate,sd.issend='1' where sd.id='{0}'",
                      dr["id"].ToString ()));
              }

          }
          catch (Exception ex) {
              LogHelp.WriteError("推送BPM报工数据异常", ex); 
              foreach (DataRow dr in dt.Rows)
              {
                  //插入writetoothersystem表
                  Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_report},
                        {"SendXml",json},{"ResXml",ex.Message +ex.StackTrace },{"IsSuccess","1"},{"ContainerID",dr["ContainerID"].ToString ()},{"WorkflowStepId",dr["WorkflowStepId"].ToString ()}
                        ,{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                  OracleDAL.InserOtherSystemRecord(recordPara);
                  //更新sendtoothersystemdata表
                  OracleHelper.ExecuteSql(string.Format("update sendtoothersystemdatadetail sd set sd.lastchangedate=sysdate,sd.issend='1' where sd.id='{0}'",
                      dr["id"].ToString()));
              }
          } 




      }

      /// <summary>
      /// 推送报工撤销信息到BPM,实际是完工撤销
      /// </summary>
      public void sendReportCycleInfoToBPM()
      {
          string strSql = @"select sd.containerid,sd.workflowstepid,sdd.id from sendtoothersystemdata sd 
inner join sendtoothersystemdatadetail sdd on sdd.sendtoothersystemdataid=sd.id
where sdd.sendtype='" + bpm_reportRecycle + "' and sdd.issend='0' and sdd.lastchangedate>=sysdate-7 and rownum<1000";

          DataTable dt = OracleHelper.Query(strSql).Tables[0];
          if (dt.Rows.Count == 0)
              return;
          DataTable jsonDt = dt.Copy();
          jsonDt.Columns.Remove("id");

          String json = JsonConvert.SerializeObject(jsonDt);

          try {
              //调用BPM接口
              LogHelp.WriteLog("推送BPM报工撤回数据：" + json);
              BpmWebService1.wzqlc_WSApi api = new BpmWebService1.wzqlc_WSApi();
              var re = api.busiService("", "MFS1004", json);
              LogHelp.WriteLog("推送BPM报工撤回数据-返回信息：" + re);

              var JsonObj = JObject.Parse(re);

              string isSuccess = "0";
              if (JsonObj["mtype"].ToString() == "S")//返回成功
              {
                  isSuccess = "0";
              }
              else
              {
                  isSuccess = "1";
              }

              foreach (DataRow dr in dt.Rows)
              {
                  //插入writetoothersystem表
                  Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_reportRecycle},
                        {"SendXml",json},{"ResXml",re},{"IsSuccess",isSuccess},{"ContainerID",dr["ContainerID"].ToString ()},{"WorkflowStepId",dr["WorkflowStepId"].ToString ()}
                        ,{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                  OracleDAL.InserOtherSystemRecord(recordPara);
                  //更新sendtoothersystemdata表
                  OracleHelper.ExecuteSql(string.Format("update sendtoothersystemdatadetail sd set sd.lastchangedate=sysdate,sd.issend='1' where sd.id='{0}'",
                      dr["id"].ToString()));
              }

          }
          catch (Exception ex) {
              foreach (DataRow dr in dt.Rows)
              {
                  //插入writetoothersystem表
                  Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",bpm_reportRecycle},
                        {"SendXml",json},{"ResXml",ex.Message +ex.StackTrace},{"IsSuccess","1"},{"ContainerID",dr["ContainerID"].ToString ()},{"WorkflowStepId",dr["WorkflowStepId"].ToString ()}
                        ,{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                  OracleDAL.InserOtherSystemRecord(recordPara);
                  //更新sendtoothersystemdata表
                  OracleHelper.ExecuteSql(string.Format("update sendtoothersystemdatadetail sd set sd.lastchangedate=sysdate,sd.issend='1' where sd.id='{0}'",
                      dr["id"].ToString()));
              }
          }


      }
    }
}
